package com.glela.goods.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.glela.cache.model.RedisKey;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.DateUtil;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.StringUtil;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;
import com.glela.goods.mapper.StoreGoodsMapper;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.StoreGoods;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.goods.service.StoreGoodsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.OperationLogService;

@Service("storeGoodsService")
@Scope("singleton")
public class StoreGoodsServiceImpl implements StoreGoodsService {

	private static Logger logger = LoggerFactory.getLogger(StoreGoodsServiceImpl.class);
	
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private StoreGoodsMapper storeGoodsMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private GoodsNavigateMapper goodsNavigateMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public Map<Long, StoreGoods> queryStoreGoods(Long userId, Collection<Long> goodsIds) {
		Map<Long, StoreGoods> rstMap = new HashMap<Long, StoreGoods>();
		List<StoreGoods> storeGoods = storeGoodsMapper.selectByGoodsIds(userId, goodsIds);
		for (StoreGoods sGoods : storeGoods) {
			if (sGoods.getGoodsId() != null && sGoods.getIsDelete() != null && sGoods.getIsDelete() == 0) {
				rstMap.put(sGoods.getGoodsId().longValue(), sGoods);
			}
		}
		return rstMap;
	}

	/**
	 * 查询店主精选产品列表
	 */
	@Override
	public List<GoodsListResponse> findStoreGoodsListByPage(Integer storeUserId, Integer topBannerId, String from, Integer startIndex, Integer pageSize) {
		List<GoodsListResponse> listGoodsListResponse = new ArrayList<GoodsListResponse>();
//		logger.info("service:============================开始列表查询==================storeUserId:"+storeUserId);
//		long startTime = System.currentTimeMillis();
		List<Goods> listGoods = this.storeGoodsMapper.selectStoreGoodsByPage(storeUserId, topBannerId/*, startIndex, pageSize*/);
//		logger.info("service:===========================列表查询结束耗时："+(System.currentTimeMillis()-startTime));
		if(listGoods == null || listGoods.size() == 0){
			return listGoodsListResponse;
		}
		User user = this.userMapper.selectByPrimaryKey(Long.valueOf(storeUserId));
		List<Long> goodsIds = new ArrayList<Long>();
		for(Goods goods : listGoods){
			goodsIds.add(goods.getId());
		}
//        logger.info("service:============================开始价格查询==================storeUserId:"+storeUserId);
//        long priceTime = System.currentTimeMillis();
		Map<Long,GoodsPrice> goodsPriceMap = this.goodsService.getGoodsViewPriceForGoods(user, goodsIds);
//        logger.info("service:============================价格查询结束耗时："+(System.currentTimeMillis()-priceTime)+"==================storeUserId:"+storeUserId);

//        logger.info("service:============================开始库存查询==================storeUserId:"+storeUserId);
//        long inventTime = System.currentTimeMillis();
		Map<Long,Long> inventoryMap = this.inventoryService.findDynaByGoodsId(goodsIds);
//        logger.info("service:============================库存查询结束耗时："+(System.currentTimeMillis()-inventTime)+"==================storeUserId:"+storeUserId);
        int i=0;
		for (Goods goods : listGoods) {
			try {
				GoodsListResponse goodsListResponse = new GoodsListResponse();
				goodsListResponse.setGoodId(goods.getId());
				goodsListResponse.setLabelName(goods.getLabelName());
				goodsListResponse.setGoodsName(goods.getName());
				goodsListResponse.setName(goods.getName());
				goodsListResponse.setTitle(goods.getTitle());
				goodsListResponse.setSuggestedPrice(goods.getSuggestedPrice());
				if(!StringUtils.isBlank(goods.getGoodsWidthPic())){
					goodsListResponse.setGoodNavigateImage(goods.getGoodsWidthPic());
				}else{
//                    logger.info("service:============================开始第："+i+"次循环查询介绍图==================storeUserId:"+storeUserId);
//                    long navigateTime = System.currentTimeMillis();
					List<GoodsNavigate> goodsNavigateList = this.goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
//                    logger.info("service:============================第："+i+"次循环查询介绍图结束耗时："+(System.currentTimeMillis()-navigateTime)+"==================storeUserId:"+storeUserId);
					goodsListResponse.setGoodNavigateImage(goodsNavigateList.get(0).getNavigateImage());
				}
				goodsListResponse.setBrandName("");
				goodsListResponse.setSelfSupport(goods.getSelfSupport());
				//价格信息
//                logger.info("service:============================开始第："+i+"次循环查询价格==================storeUserId:"+storeUserId);
//                long goodsPriceTime = System.currentTimeMillis();
				GoodsPrice goodsPrice = goodsPriceMap.get(goods.getId())==null?this.goodsService.getGoodsViewPriceForGoods(user, goods.getId()):goodsPriceMap.get(goods.getId());
//                logger.info("service:============================第："+i+"次循环查询价格结束耗时："+(System.currentTimeMillis()-goodsPriceTime)+"==================storeUserId:"+storeUserId);
				String nowTime = DateUtil.currentStringDate();
				//商品标签
				List<Map<String,String>> labelArray = new ArrayList<Map<String,String>>();
				// 状态（SecKill:秒杀中;NormalSale:原价销售;PreHeat:预热中;UnderCarriage:下架了）
				// 原价销售：没有参与分时抢购活动，且未被下架。--默认	
				// 预热中：分时抢购活动，且服务器当前时间小于秒杀活动开始时间；	 
				// 秒杀中：分时抢购活动，且服务器当前时间大于秒杀活动开始时间，小于秒杀活动结束时间；	
				// 抢光：分时抢购活动，且APP实际库存与分时抢购活动设置的库存中的最小的一个数量小于等于0；	
				// 下架：商品下架时间小于服务器当前时间或者下架时间字段为空值；	
				String saleStatus = "NormalSale";// 默认原价销售状态
				//存在goodsPrice对象为null的情况
				if(goodsPrice == null) {
					continue;
				}
				if (goodsPrice!=null) {
					Long productId = goodsPrice.getProductId();
					// 查询是否存在分时抢购活动
//                    logger.info("service:============================开始第："+i+"次循环查询分时抢购信息==================storeUserId:"+storeUserId);
//                    long limitTime = System.currentTimeMillis();
					Map<String,Object> ltsMap = this.goodsMapper.selectNearlyLimitTimeSale(goods.getId(),productId,nowTime);
//                    logger.info("service:============================第："+i+"次循环查询分时抢购信息结束耗时:"+(System.currentTimeMillis()-limitTime)+"==================storeUserId:"+storeUserId);
					if(ltsMap != null){
						Map<String,String> tmLabel = new HashMap<String, String>();
						// 分时抢购开始时间
						try {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date fullBeginTime = sdf.parse(ltsMap.get("fullBeginTime").toString());
							// 系统当前时间
							long nowTimeMillis = System.currentTimeMillis();
							if (fullBeginTime.getTime() > nowTimeMillis) {// 预热中
								saleStatus = "PreHeat";
								tmLabel.put("label", "预热");
							} else {// 抢购中
								saleStatus = "SecKill";
								tmLabel.put("label", "特卖");
							}
						} catch (ParseException e) {
							
						}
						tmLabel.put("color", "#ff4b7a");
						labelArray.add(tmLabel);
					}
				}
				// 实时库存
//                logger.info("service:============================开始第："+i+"次循环查询实时库存==================storeUserId:"+storeUserId);
//                long invenTime = System.currentTimeMillis();
				long realTimeInventory = inventoryMap.get(goods.getId())==null?0:inventoryMap.get(goods.getId());//this.inventoryService.findDynaByGoodsId(goods.getId()):inventoryMap.get(goods.getId());
//                logger.info("service:============================第："+i+"次循环查询实时库存结束耗时："+(System.currentTimeMillis()-invenTime)+"==================storeUserId:"+storeUserId);
				// 下架了
				if(goods.getOnlineTime() == null || 
						goods.getOfflineTime() == null || 
						(DateUtil.betweenTime(goods.getOnlineTime(), goods.getOfflineTime()) < 1)){
					saleStatus = "UnderCarriage";
				}
				// C区商品  设置为已下架状态
				if(goods.getGoodsType() == 0){
					saleStatus = "UnderCarriage";
				}
				goodsListResponse.setSaleStatus(saleStatus);// 销售状态
				goodsListResponse.setGoodsPrice(goodsPrice);// 价格信息
				goodsListResponse.setInventoryNum(realTimeInventory);// 库存数
				goodsListResponse.setSalerNums(goods.getUpCount());
				goodsListResponse.setLabelArray(labelArray);// 标签信息
				listGoodsListResponse.add(goodsListResponse);
				i++;
			} catch (Exception e) {
				continue;
			}
		}
		// 累加店铺分享被打开次数
		return listGoodsListResponse;
	}
	
	/**
	 * 店主精选产品上架
	 */
	@Override
	public ResponseEntity<?> addStoreGoods(StoreGoods storeGoods) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		StoreGoods querySg = new StoreGoods();
		querySg.setStoreUserId(storeGoods.getStoreUserId());
		querySg.setIsDelete(0);
		int sgCount = this.storeGoodsMapper.selectCount(querySg);
		if (Integer.valueOf(sgCount)>= CommonConstants.STORE_GOODS_NUM_MAX){
			resultMap.put("canAddNumber",0);
			resultMap.put("message","亲~精选商品已满"+CommonConstants.STORE_GOODS_NUM_MAX+"个了，不能再多啦！可以下架部分商品再上架哦。");
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40013,resultMap), HttpStatus.OK);
		}
		resultMap.put("sgCount", sgCount);
		//查询改产品是否已经在店主精选上架
		StoreGoods query = new StoreGoods();
		query.setStoreUserId(storeGoods.getStoreUserId());
		query.setTopBannerId(storeGoods.getTopBannerId());
		query.setGoodsId(storeGoods.getGoodsId());
		List<StoreGoods> storeGoodsList = this.storeGoodsMapper.selectAll(query);
		if(storeGoodsList!=null&&storeGoodsList.size()>0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40008,resultMap), HttpStatus.OK);
		}
		Goods goods = goodsMapper.selectGoodsById(storeGoods.getGoodsId());
		if (goods==null){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40009,resultMap), HttpStatus.OK);
		}
		/**
		 * 上下架次数更新到redis中，以后都从redis取
		 * 2018.01.17
		 */
		//产品上架次数+1
		//int m = this.goodsMapper.saveUpAndDownGoodsCount(storeGoods.getGoodsId(),1,0);
		//产品上架次数+1失败
		/*if(m == 0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40004,resultMap), HttpStatus.OK);
		}*/
		String storeCount = redisUtil.get(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeGoods.getStoreUserId());//storeGoodsService.selectCount(storeGoods);
		if (StringUtils.isBlank(storeCount)){
			redisUtil.set(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeGoods.getStoreUserId(),sgCount);
			/**
			 * 下个版本开放
			 */
			/*//如果没有缓存则是拿数据库统计的值，大于等于最大上架数量说明上架该商品后超过限制数量
			if (Integer.valueOf(sgCount)>= CommonConstants.STORE_GOODS_NUM_MAX){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C40013), HttpStatus.OK);
			}*/
		}/*else{
			//查询缓存时没有算正在上架的数量故大于等于限制数量时就不可再上架该商品
			if (Integer.valueOf(storeCount)>=CommonConstants.STORE_GOODS_NUM_MAX){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C40013), HttpStatus.OK);
			}
		}*/
		int n = this.storeGoodsMapper.insertSelective(storeGoods);
		if(n == 0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40004,resultMap), HttpStatus.OK);
		} else {
			try {
				OperationLog operationLog = new OperationLog();
				operationLog.setObjId(storeGoods.getGoodsId());
				operationLog.setObjName(storeGoods.getGoodsId()+"");
				operationLog.setModule("goods");
				operationLog.setOperateType("addStoreGoods");
				operationLog.setRoute("/goods/addStoreGoods");
				operationLog.setOperatorId(storeGoods.getStoreUserId());
				operationLog.setOperatorName(storeGoods.getStoreUserId()+"");
				operationLog.setCreatedAt(Math.round(System.currentTimeMillis()/1000));
				operationLog.setDescription("店主精选产品上架");
				operationLog.setIp(127001l);
				this.operationLogService.saveOperationLog(operationLog);
			} catch (Exception e) {
				
			}
		}
		sgCount += 1;
		resultMap.put("sgCount", sgCount);
		// 清楚店主精选Redis缓存
//		clearStoreGoodsListReidsCache(storeGoods.getStoreUserId(),sgCount);
		/**
		 * 更新店主精选商品列表redis
		 */
		
		
		
		String cacheKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeGoods.getStoreUserId()+ "-1";
		//上架次数递增一次
        redisUtil.incr(RedisKey.REDIS_KEY_STORE_USER_GOODS_COUNT+storeGoods.getStoreUserId());
        int upCount = goodsService.getGoodsUpDownCount(goods).getDownCount();
        
        //下面代码是用来将缓存中的产品上架数据更新至数据库中,每10分钟后人有上下架的时候触发
        String goods_upload_count_key = RedisKey.REDIS_KEY_PREFIX_MODE+RedisKey.REDIS_KEY_GOODS_FIELD_INFO+"up_count:" + storeGoods.getGoodsId()+"-expire";
		if(StringUtils.isBlank(redisUtil.get(goods_upload_count_key))) {
			if( upCount+1-goods.getUpCount() > 0) {
				goodsMapper.saveUpAndDownGoodsCount(storeGoods.getGoodsId(), (upCount+1-goods.getUpCount()), null);
				redisUtil.set(goods_upload_count_key , "1", 600);
			}
			
		}
		
		redisUtil.hmset(RedisKey.REDIS_KEY_PREFIX_MODE+RedisKey.REDIS_KEY_GOODS_FIELD_INFO+storeGoods.getGoodsId(),"up_count",(upCount+1)+"");
		
//		if (goods!=null) {
//			User user = this.userMapper.selectByPrimaryKey(Long.valueOf(storeGoods.getStoreUserId()));
//			List<Long> goodsIds = new ArrayList<Long>();
//			goodsIds.add(Long.valueOf(storeGoods.getGoodsId()));
//			Map<Long,GoodsPrice> goodsPriceMap = this.goodsService.getGoodsViewPriceForGoods(user, goodsIds);
//			Map<Long,Long> inventoryMap = this.inventoryService.findDynaByGoodsId(goodsIds);
//			GoodsListResponse goodsListResponse = new GoodsListResponse();
//			goodsListResponse.setGoodId(storeGoods.getGoodsId());
//			goodsListResponse.setLabelName(goods.getLabelName());
//			goodsListResponse.setGoodsName(goods.getName());
//			goodsListResponse.setName(goods.getName());
//			goodsListResponse.setTitle(goods.getTitle());
//			goodsListResponse.setSuggestedPrice(goods.getSuggestedPrice());
//			if(!StringUtils.isBlank(goods.getGoodsWidthPic())){
//				goodsListResponse.setGoodNavigateImage(goods.getGoodsWidthPic());
//			}else{
//				List<GoodsNavigate> goodsNavigateList = this.goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
//				goodsListResponse.setGoodNavigateImage(goodsNavigateList.get(0).getNavigateImage());
//			}
//			goodsListResponse.setBrandName("");
//			goodsListResponse.setSelfSupport(goods.getSelfSupport());
//			//价格信息
//			GoodsPrice goodsPrice = goodsPriceMap.get(goods.getId())==null?this.goodsService.getGoodsViewPriceForGoods(user, goods.getId()):goodsPriceMap.get(goods.getId());
//			String nowTime = DateUtil.currentStringDate();
//			//商品标签
//			List<Map<String,String>> labelArray = new ArrayList<Map<String,String>>();
//			// 状态（SecKill:秒杀中;NormalSale:原价销售;PreHeat:预热中;UnderCarriage:下架了）
//			// 原价销售：没有参与分时抢购活动，且未被下架。--默认	
//			// 预热中：分时抢购活动，且服务器当前时间小于秒杀活动开始时间；	 
//			// 秒杀中：分时抢购活动，且服务器当前时间大于秒杀活动开始时间，小于秒杀活动结束时间；	
//			// 抢光：分时抢购活动，且APP实际库存与分时抢购活动设置的库存中的最小的一个数量小于等于0；	
//			// 下架：商品下架时间小于服务器当前时间或者下架时间字段为空值；	
//			String saleStatus = "NormalSale";// 默认原价销售状态
//			Long productId = goodsPrice.getProductId();
//			// 查询是否存在分时抢购活动
//			Map<String,Object> ltsMap = this.goodsMapper.selectNearlyLimitTimeSale(goods.getId(),productId,nowTime);
//			if(ltsMap != null){
//				Map<String,String> tmLabel = new HashMap<String, String>();
//				// 分时抢购开始时间
//				try {
//					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//					Date fullBeginTime = sdf.parse(ltsMap.get("fullBeginTime").toString());
//					// 系统当前时间
//					long nowTimeMillis = System.currentTimeMillis();
//					if (fullBeginTime.getTime() > nowTimeMillis) {// 预热中
//						saleStatus = "PreHeat";
//						tmLabel.put("label", "预热");
//					} else {// 抢购中
//						saleStatus = "SecKill";
//						tmLabel.put("label", "特卖");
//					}
//				} catch (ParseException e) {
//					
//				}
//				tmLabel.put("color", "#ff4b7a");
//				labelArray.add(tmLabel);
//			}
//			// 实时库存
//			long realTimeInventory = inventoryMap.get(goods.getId())==null?this.inventoryService.findDynaByGoodsId(goods.getId()):inventoryMap.get(goods.getId());
//			// 下架了
//			if(goods.getOnlineTime() == null || 
//					goods.getOfflineTime() == null || 
//					(DateUtil.betweenTime(goods.getOnlineTime(), goods.getOfflineTime()) < 1)){
//				saleStatus = "UnderCarriage";
//			}
//			// C区商品  设置为已下架状态
//			if(goods.getGoodsType() == 0){
//				saleStatus = "UnderCarriage";
//			}
//			goodsListResponse.setSaleStatus(saleStatus);// 销售状态
//			goodsListResponse.setGoodsPrice(goodsPrice);// 价格信息
//			goodsListResponse.setInventoryNum(realTimeInventory);// 库存数
//			goodsListResponse.setSalerNums(goods.getUpCount());
//			goodsListResponse.setLabelArray(labelArray);// 标签信息
//			/*try {
//				this.redisUtil.lpush(cacheKey, JsonUtil.toJson(goodsListResponse));
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}*/
//			/**
//			 * 上下架次数进redis
//			 */
//		}
		//缓存改为存10分钟上下架后删除缓存
		redisUtil.del(cacheKey);
		//
		int canAddNum = CommonConstants.STORE_GOODS_NUM_MAX-sgCount>0?(CommonConstants.STORE_GOODS_NUM_MAX-sgCount):0;
		resultMap.put("canAddNumber",canAddNum);
		resultMap.put("message","上架成功 还可以上架"+canAddNum+"款商品");
		return new ResponseEntity<>(new ResponseResultModel<>(resultMap), HttpStatus.OK);
	}
	
	/**
	 * 店主精选产品下架
	 */
	@Override
	public ResponseEntity<?> removeStoreGoods(StoreGoods storeGoods) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		StoreGoods querySg = new StoreGoods();
		querySg.setStoreUserId(storeGoods.getStoreUserId());
		querySg.setIsDelete(0);
		int sgCount = this.storeGoodsMapper.selectCount(querySg);
		resultMap.put("sgCount", sgCount);
		/*//产品下架次数+1
		int m = this.goodsMapper.saveUpAndDownGoodsCount(storeGoods.getGoodsId(),0,1);
		//产品下架次数+1失败
		if(m == 0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40006,resultMap), HttpStatus.OK);
		}*/
		List<StoreGoods> storeGoodsList = this.storeGoodsMapper.selectAll(storeGoods);
		if(storeGoodsList==null||storeGoodsList.size()==0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40009,resultMap), HttpStatus.OK);
		}
		int n = this.storeGoodsMapper.deleteByPrimaryKey(storeGoodsList.get(0).getId());
		if(n == 0){
			return new ResponseEntity<>(new ResponseResultModel<>(ErrorEnum.C40006,resultMap), HttpStatus.OK);
		} else {
			try {
				OperationLog operationLog = new OperationLog();
				operationLog.setObjId(storeGoods.getGoodsId());
				operationLog.setObjName(storeGoods.getGoodsId()+"");
				operationLog.setModule("goods");
				operationLog.setOperateType("removeStoreGoods");
				operationLog.setRoute("/goods/removeStoreGoods");
				operationLog.setOperatorId(storeGoods.getStoreUserId());
				operationLog.setOperatorName(storeGoods.getStoreUserId()+"");
				operationLog.setCreatedAt(Math.round(System.currentTimeMillis()/1000));
				operationLog.setDescription("店主精选产品下架");
				operationLog.setIp(127001l);
				this.operationLogService.saveOperationLog(operationLog);
			} catch (Exception e) {
				
			}
		}
		sgCount --;
		resultMap.put("sgCount", sgCount < 0 ? 0 : sgCount);
		// 清楚店主精选Redis缓存
//		clearStoreGoodsListReidsCache(storeGoods.getStoreUserId(),sgCount);
		String cacheKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeGoods.getStoreUserId()+ "-1";
		/*try {
//			this.redisUtil.del(cacheKey);
			this.redisUtil.lremByJsonKey(cacheKey, storeGoods.getGoodsId()+"", "goodId");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("删除店主精选商品列表Redis缓存失败,删除商品ID为:"+storeGoods.getGoodsId(), e.getMessage());
		}*/
		//缓存改为存10分钟上下架后删除缓存
		redisUtil.del(cacheKey);
		/**
		 * 上下架次数进redis
		 */
		Goods upDownGoods = new Goods();
		upDownGoods.setId(storeGoods.getGoodsId());
		int downCount = goodsService.getGoodsUpDownCount(upDownGoods).getDownCount();
		
		//下面代码是用来将缓存中的产品下架数据更新至数据库中,每10分钟后人有下架的时候触发 只加不减，暂时不统计
//		Goods goods = goodsMapper.selectGoodsByIdForAll(storeGoods.getGoodsId());
//        String goods_down_count_key = RedisKey.REDIS_KEY_PREFIX_MODE+RedisKey.REDIS_KEY_GOODS_FIELD_INFO+"down_count:" + storeGoods.getGoodsId()+"-expire";
//		if(StringUtils.isBlank(redisUtil.get(goods_down_count_key))) {
//			
//			if( upCount+1-goods.getUpCount() > 0) {
//				goodsMapper.saveUpAndDownGoodsCount(storeGoods.getGoodsId(), (upCount+1-goods.getUpCount()), null);
//				redisUtil.set(goods_down_count_key , "1", 600);
//			}
//			
//		}
		
		
		redisUtil.hmset(RedisKey.REDIS_KEY_PREFIX_MODE+RedisKey.REDIS_KEY_GOODS_FIELD_INFO+storeGoods.getGoodsId(),"down_count",(downCount+1)+"");
		resultMap.put("canAddNumber",CommonConstants.STORE_GOODS_NUM_MAX-sgCount<0?0:(CommonConstants.STORE_GOODS_NUM_MAX-sgCount));
		resultMap.put("message","下架成功 精选商品共"+sgCount+"款");
		return new ResponseEntity<>(new ResponseResultModel<>(resultMap), HttpStatus.OK);
	}
	

	/**
	* *
	 * @param sgCount *********************************************
	* @Title: clearStoreGoodsListReidsCache 
	* @Description: 清除店主精选列表Redis缓存
	* @param @param storeUserId 
	* @return void
	* @throws	
	* @author NingChongQing	
	* @date 2017年12月8日 下午4:24:19 
	* **********************************************
	 */
	private void clearStoreGoodsListReidsCache(Integer storeUserId, int sgCount) {
		try {
			if (sgCount <= 0) {
				sgCount = 1;
			}
			String cacheKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeUserId + "-1-";
			int pageNum = (int) Math.ceil(BigDecimal.valueOf(sgCount).divide(BigDecimal.valueOf(10)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
			for (int i = 1; i <= pageNum; i++) {
				if (!StringUtil.isEmpty(this.redisUtil.get(cacheKey + i))) {
					this.redisUtil.del(cacheKey + i);
				}
			}
		} catch (Exception e) {
			logger.error("删除店主精选商品列表Redis缓存失败", e.getMessage());
		}
	}

	@Override
	public int selectCount(StoreGoods storeGoods) {
		// TODO Auto-generated method stub
		StoreGoods querySg = new StoreGoods();
		querySg.setStoreUserId(storeGoods.getStoreUserId());
		querySg.setIsDelete(0);
		int sgCount = this.storeGoodsMapper.selectCount(querySg);
		return sgCount;
	}

    @Override
    public void reloadStoreList(String key,Integer storeUserId, Integer topBannerId, String from, int i, int size) {
        cacheStoreList(key,storeUserId,topBannerId,from,i,size);
    }

    private static ExecutorService executorService	= Executors.newFixedThreadPool(20);

    public void cacheStoreList(final String key, final Integer storeUserId, final Integer topBannerId,final String from,final int i,final int size) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                List<GoodsListResponse> list = findStoreGoodsListByPage(storeUserId,topBannerId,from,i,size);
                String[] toBeStored = new String[list.size()];
                for (int i = 0; i <list.size() ; i++) {
                    try {
                        toBeStored[i]=JsonUtil.toJson(list.get(i));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(toBeStored != null && toBeStored.length > 0) {
                	 redisUtil.reloadList(key ,toBeStored);
                     redisUtil.set(key+"-expire","1", 300);
                }
            }
        });
    }
    
    
	public List<GoodsListResponse> readerRedisStoreGoods(int startRow,int endRow,String key){
		if(startRow > endRow) {
			return null;
		}
		List<GoodsListResponse> results = new ArrayList<GoodsListResponse>();
		
		List<String> redislist = redisUtil.lrange(key, startRow, endRow);
		for(String p : redislist) {
			GoodsListResponse goodsListResponse = JSON.parseObject(p,GoodsListResponse.class);
			results.add(goodsListResponse);
		}
		return results;		
	}
	
    
    public  boolean isStoreGoodsUpload(Long storeUserId, Long goodsId) {
    	String tempKey = "temp:com:glela:controller:StoreGoodsController:getStoreGoodsList:" + storeUserId + "-1";
    	List<GoodsListResponse> results = readerRedisStoreGoods(0,-1,tempKey);
    	if(!CollectionUtils.isEmpty(results)) {
    		for(GoodsListResponse _goods : results) {
    			if(goodsId.longValue() == _goods.getGoodId()) {
    				return Boolean.TRUE;
    			}
    		}
    	}
    	return Boolean.FALSE;
    }

}
